package com.sample.transaction.atomikos.db2.controller;

import com.sample.transaction.atomikos.db2.entity.User2;
import com.sample.transaction.atomikos.db2.service.User2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/mulDb2")
public class User2Controller {

    @Autowired
    private User2Service user2Service;

    //http://localhost:8081/mulDb2/get/id/1
    @GetMapping("/get/id/{id}")
    public User2 getUserById(@PathVariable("id")String id){
        log.info("getUserById, id = {}", id);
        return user2Service.findById(Integer.parseInt(id)).orElse(new User2());
    }

    // http://localhost:8081/mulDb2/update/1/ls/lisi
    @GetMapping("/update/{id}/{code}/{name}")
    public User2 addUser(@PathVariable("id") int id,
                         @PathVariable("code") String code, @PathVariable("name") String name, boolean throwEx){
        User2 user = new User2();
        user.setId(id);
        user.setCode(code);
        user.setName(name);
        User2 userNew = null;
        try{
            userNew = user2Service.updateUser(user,throwEx);
        }catch (RuntimeException ex){
            log.error("", ex);
        }
        return userNew;
    }

}
